<template>
  <div id="loginView">
    <div class="box">
      <div class="header">
        <div class="login">登录</div>
        <div class="register" @click="goToRegister">注册</div>
      </div>
      <div class="form-container">
        <!-- 账号密码登录表单 -->
        <a-form
          class="formInfo"
          :model="form"
          label-align="left"
          @submit="handleSubmit"
        >
          <a-form-item field="userAccount" label="账号">
            <a-input v-model="form.userAccount" placeholder="请输入账号..." />
          </a-form-item>
          <a-form-item field="userPassword" label="密码">
            <a-input
              v-model="form.userPassword"
              type="password"
              placeholder="请输入密码..."
            />
          </a-form-item>
          <a-form-item>
            <a-button html-type="submit" style="width: 100%">账号登录</a-button>
          </a-form-item>
        </a-form>

        <!-- 分隔线 -->
        <div class="separator" @click="handleWechatLogin">
          <span>微信快捷登录</span>
        </div>

        <!-- 微信扫码登录区域 -->
        <div class="wechat-login">
          <div class="qrcode-box" @click="getNewQrCode" style="cursor: pointer">
            <!-- 这里放微信登录二维码，实际项目中替换为真实接口返回的二维码 -->
            <img
              v-if="QrCodeSavePath === ''"
              src="/wechat-qrcode-placeholder.png "
              alt="微信扫码登录"
              class="qrcode"
            />
            <Qrcode
              v-else:
              :value="QrCodeSavePath"
              :size="160"
              :margin="0"
              color-dark="#000000"
              color-light="#ffffff"
              class="custom-qrcode"
            />
            <p class="qrcode-desc">请使用微信扫码登录</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onUnmounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import Qrcode from "vue-qrcode"; // 导入组件
const router = useRouter();

// 表单数据
const form = reactive({
  userAccount: "",
  userPassword: "",
});

// 账号密码登录处理
import {
  MyWxMpControllerService,
  UserControllerService,
} from "../../../generated";
import { Message } from "@arco-design/web-vue";
const handleSubmit = async () => {
  const res = await UserControllerService.userLoginUsingPost(form);
  if (res.code === 0) {
    console.log("登录成功");
    router.push("/");
  } else {
    form.userPassword = "";
    alert(res.message);
  }
};

let QrCodeSavePath = ref<string | undefined>("");
let uuid: string | undefined = "";
// 轮询定时器标识（用于清除轮询）
let pollTimer: number | null = null;
// 微信登录处理（实际项目中对接微信登录接口）
const getNewQrCode = async () => {
  // 1. 调用后端接口获取微信登录二维码ticket
  const res = await MyWxMpControllerService.getQrcodeAndUuidUsingGet();
  if (!res.data) {
    console.error("未获取到二维码信息");
    return;
  }
  // 2. 生成二维码图片（可使用qrcode.js等库）
  QrCodeSavePath.value = res.data.qrcodeUrl;
  uuid = res.data.uuid;
  // 3. 轮询检查登录状态
  startPollingLoginStatus();
};
// 轮询检查登录状态
const startPollingLoginStatus = () => {
  console.log("发起微信登录，开始轮询检查登录状态");

  // 清除旧的定时器（避免重复轮询）
  if (pollTimer) {
    clearInterval(pollTimer);
  }

  // 每3秒检查一次登录状态（间隔可根据需求调整）
  pollTimer = window.setInterval(async () => {
    try {
      // 调用后端接口查询登录状态
      const res = await MyWxMpControllerService.wxMpUserIsLoginUsingPost(uuid);
      if (res.data === 1) {
        // 登录成功：清除轮询，跳转首页
        clearPolling();
        console.log("微信登录成功，跳转首页");
        router.push("/"); // 跳转到登录后的页面
      }
      if (res.data === -1) {
        // 验证码过期：清除轮询，提示验证码过期
        clearPolling();
        QrCodeSavePath.value = "";
        Message.error("验证码过期");
      }
      // 未过期且未登录：继续轮询（不做处理） res.code == 0
    } catch (error) {
      console.error("轮询登录状态失败:", error);
      // 错误处理：可尝试重试或提示用户
      clearPolling();
      setTimeout(getNewQrCode, 3000); // 3秒后重试
    }
  }, 3000); // 3秒轮询一次
};

// 清除轮询定时器
const clearPolling = () => {
  if (pollTimer) {
    clearInterval(pollTimer);
    pollTimer = null;
    console.log("停止轮询登录状态");
  }
};
// 页面卸载时清除轮询（防止内存泄漏）
onUnmounted(() => {
  clearPolling();
});
// 切换到注册页面
const goToRegister = () => {
  router.push("/user/register");
};
</script>

<style>
#loginView .box {
  background-color: #efefef;
  width: 350px; /* 适当加宽以容纳扫码区域 */
  min-height: 500px;
  margin: 50px auto auto auto;
  border-radius: 8px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

#loginView .box .header {
  display: flex;
  height: 50px;
}

#loginView .box .header .login {
  background-color: #5a55ee;
  flex: 2; /* 用flex布局更灵活 */
  font-size: 30px;
  line-height: 50px;
  text-align: center;
  color: white;
}

#loginView .box .header .register {
  background-color: #a8ee69;
  flex: 1;
  font-size: 15px;
  line-height: 50px;
  text-align: center;
}

#loginView .box .header .login:hover,
#loginView .box .header .register:hover {
  cursor: pointer;
  opacity: 0.9;
}

.form-container {
  padding: 20px;
}

.formInfo {
  margin-bottom: 0px;
}

/* 分隔线样式 */
.separator {
  display: flex;
  align-items: center;
  margin: 10px 0;
  cursor: pointer;
}

.separator::before,
.separator::after {
  content: "";
  flex: 1;
  height: 1px;
  background-color: #ccc;
}

.separator span {
  padding: 0 10px;
  font-size: 14px;
  color: #666;
}

/* 微信登录区域 */
.wechat-login {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.qrcode-box {
  text-align: center;
}

.qrcode {
  width: 160px;
  height: 160px;
  padding: 0px;
  background-color: white;
  border-radius: 4px;
}

.qrcode-desc {
  margin-top: 10px;
  font-size: 14px;
  color: #555;
}

/* 强制设置宽高为 160px */
.custom-qrcode {
  width: 160px !important;
  height: 160px !important;
}
</style>
